// This file is part of SyncStar, free software released under GPL v2.
package com.syncstar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;

/** Listens for global system-wide and application-wide events. */
public class GlobalReceiver extends BroadcastReceiver {
  private static final String TAG = GlobalReceiver.class.getSimpleName();
  static boolean isFirstActivityCreate = true;

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.e(TAG, "CONNX rec action=" + intent.getAction());
    if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
      SyncService.maybeSyncNow(context, true);
    } else if (ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED.equals(intent.getAction())) {
      SyncService.maybeSyncNow(context, true);
      SyncService.maybeStartOrStopBackgroundScheduled(context);
    } else if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
      context.getSharedPreferences("lastsync", 0).edit()
          .remove("happened_since_boot").commit();
      SslUtils.setupPermissiveSslCertificateVerification(context);
      int status = SyncService.maybeSyncNow(context, true);
      if (status != SyncService.STATUS_ALREADY &&
          status != SyncService.STATUS_STARTED_NOW) {
        // The if above is superfluous, but we just play safe.
        PopulateService.populatePresenceTableNowOrLater(context);
      }
      SyncService.maybeStartOrStopBackgroundScheduled(context);
    }
  }

  /** Must be called in the UI thread in an activity.onCreate().
   * @param context context
   */
  static void onActivityCreate(Context context) {
    if (isFirstActivityCreate) {
      isFirstActivityCreate = false;
      onAppStart(context);
    }
  }

  /** Must be called in the UI thread.
   * @param context context
   */
  static void onAppStart(Context context) {
    SslUtils.setupPermissiveSslCertificateVerification(context);
    SmsUtils.populatePresenceTable(context, -1);
    SyncService.maybeStartOrStopBackgroundScheduled(context);
    PopulateService.populatePresenceTableNowOrLater(context);
    context.startService(new Intent(context, UpdateService.class));
  }

}
